<cfset sDateNow = CreateODBCDate(Now())>
<CFQUERY NAME="checkEntry" DATASOURCE="#client.company_dsn#">
	SELECT * FROM CINWORKSCHED
	WHERE WSCODE_FK = '#sID#'
		AND WSNUMBER='#wsIDnum#'
</CFQUERY>
<CFSET sReRoute=FALSE>
<CFIF checkEntry.APPROVED EQ "R">
	<CFSET sReRoute=TRUE>
</CFIF>
<CFIF sWarn EQ "">
	<CFTRY>
	<!--- get the activity code involved (first record)--->
	<CFQUERY NAME="GetInvAct" DATASOURCE="#client.company_dsn#">
		SELECT ACTIVITYID, MAPPING, ROLECODE, UNITCODE
		FROM CINFFACTIVITY
		WHERE  (PROCESSCODE = '#theProcess#')
		ORDER BY ORDERID
	</CFQUERY>
	<!--- If Form is re-routed or not (from returned to originator)... - winston--->
	<CFIF sReRoute IS FALSE>
		<CFSET sRouteID = #CreateUUID()#>
		<CFSET sCurrentSequence = 1>
		<CFSET sStarted = "STARTED">
		<CFSET sInitialization = "INITIALIZATION">
	<CFELSE>
		<CFSET sMess = "Re-Route.<BR>">
		<CFSET sRouteID = checkEntry.ROUTEID>
		<CFQUERY NAME="checkCurrSequence" DATASOURCE="#client.company_dsn#">
			SELECT MAX(CURRENTSEQUENCE) AS CURRENTSEQUENCE
			FROM CRGROUTEDETAILS
			WHERE (ROUTEID = '#sRouteID#')
		</CFQUERY>
		<CFSET sCurrentSequence = checkCurrSequence.CURRENTSEQUENCE + 1>
		<CFSET sStarted = "RE-ROUTE">
		<CFSET sInitialization = "#GetInvAct.ACTIVITYID#">
	</CFIF>

	<!--- update the record itself --->
	<!--- Start --->
	<CFINCLUDE TEMPLATE="_saveoverride.cfm">
	<!--- End --->

	<CFIF sReRoute IS FALSE>
		<!--- log to master router --->
		<CFQUERY NAME="SaveRouteMaster" DATASOURCE="#client.company_dsn#">
			INSERT
			INTO CRGROUTEMAIN
				(ROUTEID, DESCRIPTION, TABLENAME_FK,
				ORIGINATOR, PRIORITY, ORGENTITY, INCLUDEEFORM, ROUTEPARAMS,
				RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
			VALUES
				('#sRouteID#', '#checkEntry.WSDESCRIPTION#', 'CINWORKSCHED',
				'#client.userid#', '2', '', 'N',
				'levelid="C"|subcompanycode=""',
				'#client.userid#', #sDateNow#,
				'#client.userid#', #sDateNow#,
				'#TIMEFORMAT(Now(), "hh:mmtt")#')
		</CFQUERY>
	</CFIF>
	<!---ADDED BY JEP, TO REMOVE FROM WORKLIST--->
	<CFIF sReRoute>
		<CFQUERY NAME="SaveRouteDetail" DATASOURCE="#client.company_dsn#">
			UPDATE CRGROUTERECORDS
			SET ISHIDE='Y'
			WHERE ISHIDE='N'
				AND ROUTEID='#sRouteID#'
		</CFQUERY>
	</CFIF>
	<!---ENDS HERE--->
	<CFQUERY NAME="SaveRouteDetail" DATASOURCE="#client.company_dsn#">
		INSERT
		INTO CRGROUTEDETAILS
			(ROUTEID, ORDERID, CURRENTSEQUENCE, ROUTER, ROUTERREMARKS, STATUS, ACTIVITYID,
		 	RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
		VALUES
			('#sRouteID#', 1, '#sCurrentSequence#', '#client.userid#', '', '#sStarted#', '#sInitialization#',
			'#client.userid#',
			#sDateNow#,
			'#client.userid#',
			#sDateNow#,
			'#TIMEFORMAT(Now(), "hh:mm:tt")#')
	</CFQUERY>
	<CFQUERY NAME="SaveRouteRec" DATASOURCE="#table_dsn#">
		UPDATE CINWORKSCHED
		SET
			ROUTEID = '#sRouteID#',
			APPROVED = 'S'
		WHERE WSCODE_FK = '#sID#'
			AND WSNUMBER='#wsIDnum#'
			AND PERSONNELIDNO = '#CLIENT.CHAPA#'
	</CFQUERY>
	<CFSET sMess = sMess & "Form routing successfully initialized.<BR>">

	<!--- trap errors --->
	<CFCATCH>
		<CFSET sWarn = #CFCATCH.message# & #CFCATCH.DETAIL#>
	</CFCATCH>
	</CFTRY>
</CFIF>

<CFIF sWarn EQ "">
	<CFTRY>


	<!--- initilize mail and msg variables --->
	<CFSET sMailRecipients = "">
	<CFSET sRecordID = CreateUUID()>
	<CFSET sMsgRecipients = "">
	<CFSET sIntendedRecipient="">
	<CFSET sPerSuperior = "">

	<CFSWITCH EXPRESSION="#lcase(GetInvAct.MAPPING)#">

		<!--------------------------------------->
		<!--- the originator is the recipient --->
		<!--------------------------------------->
		<CFCASE VALUE="originator">
			<!--- this cannot be, it is invalid! --->
			<CFMODULE TEMPLATE="#client.common_path#cfm_workspace.cfm" MODULE="#session.tabId#" LOCATION="#session.tabLocation#" COMPONENT="Error in form-flow process">
			<BR><BR>
			<H3>Invalid mapping.</H3>
			<CFOUTPUT>
			Originator to Originator mapping is not allowed.
			Please notify your iBOS/e Administrator.
			</CFOUTPUT>
			<CFMODULE TEMPLATE="#client.common_path#cfm_workspace.cfm" TOP="False">
			<CFABORT>
		</CFCASE>

		<!-------------------------------------------------->
		<!--- extract the recipient through the unitcode --->
		<!-------------------------------------------------->
		<CFCASE VALUE="userrole">
			<!--- get intended recipients --->
			<CFQUERY NAME="GetRecipients" DATASOURCE="#client.global_dsn#">
				SELECT USERGRPMEMBERSIDX, GUID FROM EGRGROLEINDEX, EGRGUSERMASTER
				WHERE
					EGRGUSERMASTER.USERID = EGRGROLEINDEX.USERGRPMEMBERSIDX AND
					USERGRPID_FK = '#GetInvAct.ROLECODE#';
			</CFQUERY>

			<!--- if sole individual in role, SIYA NA! --->
			<CFIF GetRecipients.RecordCount EQ 1>
				<CFMODULE TEMPLATE="#client.common_path#cfm_getuser.cfm" USERID="#GetRecipients.USERGRPMEMBERSIDX#">
				<CFIF ISFOUND>
					<!--- log to route records --->
					<CFQUERY NAME="SaveRouteRecords" DATASOURCE="#client.company_dsn#">
						INSERT
						INTO CRGROUTERECORDS
							(USERID_FK, ROUTEDATE, ROUTETIME, ORIGINATOR,
							PROCESSCODE, ACTIVITYID, ROUTEID,
							ISNEW, ISHIDE, RECORDID,
							RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
						VALUES
							('#GetRecipients.USERGRPMEMBERSIDX#',
							#sDateNow#,
							'#TIMEFORMAT(Now(), "HH:mm:ss")#', '#client.userid#',
							'#theProcess#', '#GetInvAct.ACTIVITYID#', '#sRouteID#',
							'Y','N', '#sRecordID#',
							'#client.userid#',
							#sDateNow#,
							'#client.userid#',
							#sDateNow#,
							'#TIMEFORMAT(Now(), "hh:mmtt")#')
					</CFQUERY>

					<CFSET sMsgRecipients  = sMsgRecipients  & "(" & PERID & ") " & PERNAME & ", ">
					<CFSET sMailRecipients=PERADDRESS>
					<CFSET sIntendedRecipient=GetRecipients.USERGRPMEMBERSIDX>
				</CFIF>	<!--- recipient is valid --->
			<CFELSE>
				<!--- set unitcode to use --->
				<CFSET sUnitCode2Use=Trim(GetInvAct.UNITCODE)>
				<CFIF sUnitCode2Use IS "">
					<CFSET sUnitCode2Use="UNITCODE">
				</CFIF>

				<!--- get the userid that override members in userrole --->
				<CFQUERY NAME="overridemapping" DATASOURCE="#client.company_dsn#">
					SELECT *
					FROM ECMFUSRDEFINEROLE
					WHERE ROUTEID = '#sRouteID#' AND
						  ACTIVITYID = '#GetInvAct.ACTIVITYID#'
				</CFQUERY>
				<CFSET sCode2Use=Trim(overridemapping.USERID)>

				<CFLOOP QUERY="GetRecipients">
					<CFIF sCode2Use IS "">
						<!--- in case overriding of members in userrole is not
							done by the user before routing the form,
							mapping will re-route to any member of the
							userrole with same unitcode as of the originator --->
						<CFQUERY NAME="GetEntity" DATASOURCE="#client.company_dsn#">
							SELECT #sUnitCode2Use#
							FROM CMFPA
							WHERE GUID = '#GetRecipients.GUID#'
						</CFQUERY>
						<CFSET lContinue="Yes">
					<CFELSEIF sCode2Use IS GetRecipients.USERGRPMEMBERSIDX>
						<CFSET lContinue="Yes">
					<CFELSE>
						<CFSET lContinue="No">
					</CFIF>

					<CFIF lContinue>
						<CFMODULE TEMPLATE="#client.common_path#cfm_getuser.cfm" USERID="#GetRecipients.USERGRPMEMBERSIDX#">
						<CFIF ISFOUND>
							<!--- in case overriding of members in userrole is not
								done by the user before routing the form,
								mapping will re-route to any member of the
								userrole with same unitcode as of the originator --->
							<CFIF sCode2Use IS "">
								<CFQUERY NAME="getdivision" DATASOURCE="#client.company_dsn#">
									SELECT #sUnitCode2Use#
									FROM CMFPA
									WHERE PERSONNELIDNO = '#client.chapa#'
								</CFQUERY>
							</CFIF>

							<CFIF (sCode2Use IS NOT "") OR
								  (
								  	GetEntity.RecordCount AND
									getdivision.RecordCount AND
									ucase(Evaluate("GetEntity." & sUnitCode2Use)) EQ
									ucase(Evaluate("getdivision." & sUnitCode2Use))
								  )
							>
								<!--- log to route records --->
								<CFQUERY NAME="SaveRouteRecords" DATASOURCE="#client.company_dsn#">
									INSERT
									INTO CRGROUTERECORDS
										(USERID_FK, ROUTEDATE, ROUTETIME, ORIGINATOR,
										PROCESSCODE, ACTIVITYID, ROUTEID,
										ISNEW, ISHIDE, RECORDID,
										RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
									VALUES
										('#GetRecipients.USERGRPMEMBERSIDX#',
										#sDateNow#,
										'#TIMEFORMAT(Now(), "HH:mm:ss")#', '#client.userid#',
										'#theProcess#', '#GetInvAct.ACTIVITYID#', '#sRouteID#',
										'Y','N', '#sRecordID#',
										'#client.userid#',
										#sDateNow#,
										'#client.userid#',
										#sDateNow#,
										'#TIMEFORMAT(Now(), "hh:mmtt")#')
								</CFQUERY>

								<CFSET sIntendedRecipient=GetRecipients.USERGRPMEMBERSIDX>
								<CFSET sMsgRecipients  = sMsgRecipients  & "(" & PERID & ") " & PERNAME & ", ">
								<CFSET sMailRecipients=PERADDRESS>
							</CFIF>	<!--- unitcode of originator is the same with the recipient --->
						</CFIF>	<!--- recipient is validated --->
					</CFIF>
				</CFLOOP>
			</CFIF>
		</CFCASE>

		<!----------------------------------------------->
		<!--- the immediate superior is the recipient --->
		<!----------------------------------------------->
		<CFDEFAULTCASE> <!--- superior --->
			<CFMODULE TEMPLATE="#client.common_path#cfm_getuser.cfm" USERID="#client.userid#">
			<CFIF ISFOUND>
				<CFIF Trim(PERSUPERIOR) NEQ "">
					<CFQUERY NAME="GetCode" DATASOURCE="#client.company_dsn#">
						SELECT GUID, PERSONNELIDNO, LASTNAME #sqlCONCAT# ', ' #sqlCONCAT# FIRSTNAME #sqlCONCAT# ' ' #sqlCONCAT# MIDDLENAME AS NAME
						FROM CMFPA
						WHERE PERSONNELIDNO = '#PERSUPERIOR#'
					</CFQUERY>

					<CFIF GetCode.RecordCount>
						<!--- extract profile name --->
						<CFQUERY NAME="GetProfileName" DATASOURCE="#client.global_dsn#">
							SELECT USERID, PROFILENAME
							FROM EGRGUSERMASTER
							WHERE GUID = '#GetCode.GUID#'
						</CFQUERY>

						<CFIF GetProfileName.RecordCount>
							<CFSET sIntendedRecipient=GetProfileName.USERID>
							<!--- log to route records --->
							<CFQUERY NAME="SaveRouteRecords" DATASOURCE="#client.company_dsn#">
								INSERT
								INTO CRGROUTERECORDS
									(USERID_FK, ROUTEDATE, ROUTETIME, ORIGINATOR,
									PROCESSCODE, ACTIVITYID, ROUTEID,
									ISNEW, ISHIDE, RECORDID,
								 	RECCREATEDBY, RECDATECREATED, USERID, DATELASTUPDATE, TIMELASTUPDATE)
								VALUES
									('#GetProfileName.USERID#',
									#sDateNow#,
									'#TIMEFORMAT(Now(), "HH:mm:ss")#', '#client.userid#',
									'#theProcess#', '#GetInvAct.ACTIVITYID#', '#sRouteID#',
									'Y','N', '#sRecordID#',
									'#client.userid#',
									#sDateNow#,
									'#client.userid#',
									#sDateNow#,
									'#TIMEFORMAT(Now(), "hh:mmtt")#')
							</CFQUERY>

							<CFSET sIntendedRecipient=GetProfileName.USERID>
							<CFSET sMailRecipients=Trim(GetProfileName.PROFILENAME)>
							<CFSET sMsgRecipients = sMsgRecipients  & "(" & GetCode.PERSONNELIDNO & ") " & GetCode.NAME>
						<CFELSE>
							<CFMODULE TEMPLATE="#client.common_path#cfm_error.cfm" MODULE="#session.tabid#" TYPE="SUPERIORNOIBOSE">
						</CFIF> <!--- profile not found --->
					<CFELSE>
						<CFMODULE TEMPLATE="#client.common_path#cfm_error.cfm" MODULE="#session.tabid#" TYPE="SUPERIORNOTEXIST">
					</CFIF> <!--- Approving party's superior doesn't exist in CMFPA --->
				<CFELSE>
					<CFSET sPerSuperior = "">
					<CFMODULE TEMPLATE="#client.common_path#cfm_error.cfm" MODULE="#session.tabid#" TYPE="NOSUPERIOR">
				</CFIF> <!--- Approving party doesn't have superior --->
			</CFIF>
		</CFDEFAULTCASE>
	</CFSWITCH>
	<!--- ************************************************************* --->
	<!--- ************************************************************* --->
	<!--- ******    THE ROUTING PATH IS DEFINED AND EXTRACTED   ******* --->
	<!--- ******    THE PROCESS ENDS HERE                       ******* --->
	<!--- ************************************************************* --->
	<!--- ************************************************************* --->

	<CFIF sIntendedRecipient IS "">
		<CFMODULE TEMPLATE="#client.common_path#cfm_workspace.cfm" MODULE="#session.tabId#" LOCATION="#session.tabLocation#" COMPONENT="Error in form-flow process">
		<BR><BR>
		<H3>Intended Recipient is missing.</H3>
		Please notify your iBOS/e Administrator.
		<CFMODULE TEMPLATE="#client.common_path#cfm_workspace.cfm" TOP="False">
		<CFABORT>
	</CFIF>

	<!--- get the process of eform for eform follow-up and forwarding --->
	<CFQUERY NAME="qryCINFFPROCESS" DATASOURCE="#client.company_dsn#">
		SELECT ISFOLLOW, FOLLOWHOURS, ISFORWARD, FORWARDHOURS
		FROM CINFFPROCESS
		WHERE (PROCESSCODE = '#theProcess#')
	</CFQUERY>

	<CFIF UCase(qryCINFFPROCESS.ISFOLLOW) IS "Y" AND qryCINFFPROCESS.FOLLOWHOURS GT 0>
		<CFSET lFollowUp=true>
	<CFELSE>
		<CFSET lFollowUp=false>
	</CFIF>
	<CFIF UCase(qryCINFFPROCESS.ISFORWARD) IS "Y" AND qryCINFFPROCESS.FORWARDHOURS GT 0>
		<CFSET lForward=true>
	<CFELSE>
		<CFSET lForward=false>
	</CFIF>

	<!--- set variables for followup or forwarding --->
	<CFIF lFollowUp OR lForward>
		<!--- remove http:// in parameters --->
		<CFIF LCase(Left(client.mailtransporturl, 7)) IS "http://">
			<CFSET sMailTransportURL=Mid(client.mailtransporturl, 8, Len(client.mailtransporturl))>
		<CFELSE>
			<CFSET sMailTransportURL=client.mailtransporturl>
		</CFIF>
		<CFSET sMailTransportURL=URLEncodedFormat(sMailTransportURL)>
	</CFIF>

	<!--- create schedule for follow-up --->
	<!--- Start --->
	<CFIF lFollowUp AND sMailRecipients IS NOT "">
		<CFSET sURL=client.domain & "schedule/followmail.cfm?mailtransporturl=" & sMailTransportURL &
				"&mailserver=" & URLEncodedFormat(client.mailserver) &
				"&mailbox=" & URLEncodedFormat(client.mailbox) &
				"&userid=" & URLEncodedFormat(sIntendedRecipient) &
				"&mailcontent=" & URLEncodedFormat(client.mailcontent) &
				"&sender=" & URLEncodedFormat(client.myname) &
				"&urldomain=" & "#client.domain#" &
				"&url3=" & URLEncodedFormat(client.companycode) &
				"&url4=" & URLEncodedFormat(sRecordID) &
				"&from=" & URLEncodedFormat(LCase(client.profilename)) &
				"&to=" & URLEncodedFormat(LCase(sMailRecipients)) &
				"&dsn=" & client.company_dsn &
				"&ek=" & URLEncodedFormat(client.ek) &
				"&compname=" & URLEncodedFormat(client.companyname) &
				"&formgroup=" & URLEncodedFormat(GetForm.formgroup) &
				"&formdescription=" & URLEncodedFormat(GetForm.description)>
		<CFIF lForward>
			<CFSET sURL=sURL & "&forward=" & qryCINFFPROCESS.FORWARDHOURS>
		<CFELSE>
			<CFSET sURL=sURL & "&followup=" & qryCINFFPROCESS.FOLLOWHOURS>
		</CFIF>

		<CFSET nFollowHours = qryCINFFPROCESS.FOLLOWHOURS * 60>
		<CFSCHEDULE ACTION="Update"
			TASK="follow#sRecordID#"
			OPERATION="HTTPRequest"
			STARTDATE="#Now()#"
			STARTTIME="#TimeFormat(DateAdd('n', qryCINFFPROCESS.FOLLOWHOURS, Now()))#"
			URL="#sURL#"
			INTERVAL="#nFollowHours#">
	</CFIF>
	<!--- End --->

	<!--- create schedule for forwarding --->
	<!--- Start --->
	<CFIF lForward>
		<!--- get recipients alternate approver --->
		<CFMODULE TEMPLATE="#client.common_path#routing/routefunc_getalternate.cfm"
			USERID="#sIntendedRecipient#">

		<CFIF ALTERNATE NEQ "">
			<!--- Create alternate approver schedule --->
			<CF_IBOSELOG MODULE="EWORKSKED:UPDATE&ROUTE" LEVEL="INFORMATION" FILE="_saverouteMAPISMTP.cfm"
				MESSAGE="Created schedule for alternate approver: USERID=#sIntendedRecipient#, ALTERNATE=#ALTERNATE#.">
			<CFMODULE TEMPLATE="#client.common_path#routing/routefunc_createsched.cfm"
				MAILTRANSPORTURL = "#sMailTransportURL#"
				USERID = "#sIntendedRecipient#"
				RECORDID = "#sRecordID#"
				PROCESSID = "#theProcess#"
				ACTIVITYID = "#GetInvAct.ACTIVITYID#"
				ROUTEID = "#sRouteID#"
				TABLE_DSN = "#table_dsn#"
				TABLENAME = "#GetForm.TABLENAME_FK#"
				FORMGROUP = "#GetForm.formgroup#"
				FORMDESC = "#GetForm.description#"
				FORWARDHOURS = "#qryCINFFPROCESS.FORWARDHOURS#"
				ALTAPPROVER = "#ALTERNATE#"
				ALTAPPROVERCOUNT = "1"
				ORIGAPPROVER = "#sIntendedRecipient#"
				COMPNAME="#client.companyname#"
				>
		</CFIF>
	</CFIF>
	<!--- End --->

	<!--- trap errors --->
	<CFCATCH>
		<CFSET sWarn = #CFCATCH.message# & #CFCATCH.DETAIL#>
	</CFCATCH>
	</CFTRY>
</CFIF>

<CFIF sWarn EQ "">
	<!--- clean and go --->
	<CFIF sMailRecipients IS NOT "" and client.profilename NEQ "">
		<CFMAIL FROM="#LCase(client.profilename)#"
				TO="#LCase(sMailRecipients)#"
				SUBJECT="#client.mailcontent# Message(Routing Form)"
				TYPE="HTML">

			<FONT color="Maroon" style="font: 21px Arial">#client.companyname#</FONT><br>
			<FONT color="Maroon" style="font: 20px Arial">iBOS/e WebShell 2005 Routing Form</FONT><br>
			<TABLE border="1" cellpadding="3" cellspacing="3" style="font: 13px Arial" width = 400>
			<TR><TD width=30%><strong>eWorksked Name</strong></TD><TD width=70%>#checkEntry.WSdescription#</TD></TR>
			<TR><TD width=30%><strong>Sender</strong></TD><TD width=70%>#client.myname#</TD></TR>

			<CFIF #GetForm.ENABLEMAILAPPROV# NEQ "Y">
				<TR>
				<TD width=30%><strong>Message</strong></TD>
				<TD width=70%>You have a new work item.<BR>
				<A HREF="#client.domain#eworksched/routing/route.cfm?autolog=yes&userid=#sIntendedRecipient#&companyid=#client.companycode#&id=#URLEncodedFormat(Encrypt(sRecordID, client.ek))#&lastandread=no">Click here to view.</A></TD>
				</TR>
			</CFIF>
			</TABLE>
			<BR>
		</CFMAIL>
	</CFIF>
	<CFSET sMess = sMess & "Form forwarded to #sMsgRecipients#.<BR>">
</CFIF>
